package com.ppl.server.resources;

import com.sun.jersey.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * User: Vincent
 * Date: 11/20/12
 * Time: 4:29 PM
 */

@Path("/http/upload")
public class UploadAction {
    Logger log = LoggerFactory.getLogger(getClass());

    @Path("/file")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public Response uploadTest(@FormDataParam("file") InputStream imageStream,@FormDataParam("title") String title,@FormDataParam("description") String description){
        String location = "/images/test/"+System.currentTimeMillis()+"_"+ UUID.randomUUID().toString()+".jpeg";
        try {
            BufferedImage bi = ImageIO.read(imageStream);
            ImageIO.write(bi,"image/jpeg",new File(location));

        } catch (IOException e) {
            log.debug("", e);
        }

        return Response.ok(new String[]{"location:"+location,"title:"+title,"description:"+description}).build();
    }

    @Path("/test")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response uploadJson(ImageRequest request){
        String file = request.getFile();
        String title = request.getTitle();
        String description = request.getDescription();


        return Response.ok(new String[]{title,description}).build();
    }

    public class ImageRequest{
        private String file;
        private String title;
        private String description;

        public String getFile() {
            return file;
        }

        public void setFile(String file) {
            this.file = file;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }
}
